package com.wanchuang.qhbb.module.policy;

/**
 * 文件名 : EaringDetailFragment
 * 创建者 : MangoWang
 * 创建日期 : 2019/11/28 20:47
 * 微信 : MangoWaWang
 * 邮箱 : 763482205@qq.com
 * 描述 : TODO
 */

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.entity.node.BaseNode;
import com.wanchuang.qhbb.R;
import com.wanchuang.qhbb.base.BaseFragment;
import com.wanchuang.qhbb.net.Apis;
import com.wanchuang.qhbb.net.NetworkManager;
import com.wanchuang.qhbb.net.interfaces.OnRequestCallBack;
import com.wanchuang.qhbb.proto.AgentPolicy;
import com.wanchuang.qhbb.view.treeopen.FirstNode;
import com.wanchuang.qhbb.view.treeopen.NodeSectionAdapter;
import com.wanchuang.qhbb.view.treeopen.SecondNode;

import com.google.protobuf.InvalidProtocolBufferException;


import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;


public class PolicyChangeFragment extends BaseFragment {

    Unbinder unbinder;

    @BindView(R.id.fragment_recycleView)
    RecyclerView fragmentRecycleView;

    private int position;
    private NodeSectionAdapter adapter;


    public static PolicyChangeFragment NewInstance(int instanceType) {
        Bundle bundle = new Bundle();
        bundle.putInt("position", instanceType);
        PolicyChangeFragment messageTypeFragment = new PolicyChangeFragment();
        messageTypeFragment.setArguments(bundle);
        return messageTypeFragment;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }


    /**
     * 获取布局文件
     *
     * @return
     */
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_recycleview;
    }


    /**
     * 初始化操作步骤
     */
    @Override
    protected void init() {
        unbinder = ButterKnife.bind(this, rootView);
        position = getArguments().getInt("position");
    }

    /**
     * 初始化界面
     */
    @Override
    protected void initView() {
        initRecycle();
        initData();
    }

    /**
     * 实例化线性底部RecyclerView
     * *
     */
    private void initRecycle() {
        adapter = new NodeSectionAdapter();
        fragmentRecycleView.setAdapter(adapter);
        fragmentRecycleView.setLayoutManager(new LinearLayoutManager(mContext));
        // 先注册需要点击的子控件id（注意，请不要写在convert方法里）
        adapter.addChildClickViewIds(R.id.tv_tong_yi, R.id.tv_ju_jue, R.id.tv_dai);

        adapter.setEmptyView(R.layout.recycle_empty);
        // 设置子控件点击监听
        adapter.setOnItemChildClickListener((adapter1, view, position) -> {
            if (view.getId() == R.id.tv_tong_yi) {
                changPolicy(((FirstNode) adapter1.getData().get(position)).getPolicyLog().getId(), "2");
            } else if (view.getId() == R.id.tv_ju_jue) {
                changPolicy(((FirstNode) adapter1.getData().get(position)).getPolicyLog().getId(), "3");
            }
        });
    }

    private void changPolicy(String id, String examine_type) {
        AgentPolicy.modify_partner_policy.Builder builder = AgentPolicy.modify_partner_policy.newBuilder();
        builder.setExamineType(examine_type).setId(id);
        NetworkManager.INSTANCE.post(Apis.modify_partner_policy, builder.build().toByteArray(), new OnRequestCallBack() {
            @Override
            public void onOk(byte[] bytes) {

            }

            @Override
            public void onError(int code, String errorMessage) {
                if (code == 200) {
                    adapter.setNewInstance(new ArrayList<>());
                    initData();
                }
                showToast(errorMessage);
            }
        });

    }


    private void initData() {
        NetworkManager.INSTANCE.post(Apis.get_modify_policy_logs, new OnRequestCallBack() {
            @Override
            public void onOk(byte[] bytes) throws InvalidProtocolBufferException {
                AgentPolicy.get_modify_policy_logs result = AgentPolicy.get_modify_policy_logs.parseFrom(bytes);
                Log.e("get_modify_policy_logs", result.toString());
                //总的 list，里面放的是 FirstNode
                List<BaseNode> list = new ArrayList<>();
                for (int i = 0; i < result.getModifyPolicyLogsCount(); i++) {
                    //SecondNode 的 list
                    List<BaseNode> secondNodeList = new ArrayList<>();
                    // 切割
                    String[] splits = result.getModifyPolicyLogs(i).getDetailMsg().split("\\|");
                    for (int n = 0; n < splits.length; n++) {
                        SecondNode seNode = new SecondNode(splits[n]);
                        if (n == splits.length - 1) {
                            seNode.setLine(true);
                        }
                        secondNodeList.add(seNode);
                    }
                    FirstNode entity = new FirstNode(secondNodeList, result.getModifyPolicyLogs(i));
                    list.add(entity);
                }
                adapter.addData(list);
            }


            @Override
            public void onError(int code, String errorMessage) {
                if (!TextUtils.isEmpty(errorMessage)) showToast(errorMessage);
            }
        });
    }

    public void reload() {
        adapter.setNewInstance(new ArrayList<>());
        initData();
    }


}
